package io.gitee.caoxiaoyu97.lifecycle.lifecyle.netty;

import io.gitee.caoxiaoyu97.lifecycle.lifecyle.BftsSmartLifecycle;
import io.netty.channel.ChannelHandler;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Component;

import java.util.concurrent.ThreadPoolExecutor;

/*********************************************************
 * 文件名称：SecuServer.java
 * 系统名称：交易银行系统V2.0
 * 模块名称：com.hundsun.ifts.nbyh.pre
 * 功能说明：接收券商消息的服务
 * 开发人员 @author：caoxy31978
 * 开发时间 @date：2022/8/24 19:30
 * 修改记录：程序版本  修改日期  修改人员  修改单号  修改说明
 *********************************************************/
@Component
public class SecuServer extends AbstractServer implements BftsSmartLifecycle {
    private ThreadPoolTaskExecutor taskExecutor;

    private boolean isRunning = false;

    @Override
    public ChannelHandler[] getHandler() {
        // return new ChannelHandler[]{new SecuNettySocketChoiceHandler()};
        return null;
    }

    @Override
    public int getPort() {
        // return ConfigUtils.get("tbsp.adapter.socket.bfts.server.port", Integer.class, 3809);
        return 3809;
    }


    @Override
    public int getTimeOut() {
        // return ConfigUtils.get("tbsp.adapter.socket.bfts.server.so.timeout", Integer.class, super.getTimeOut());
        return 180;
    }

    public ThreadPoolTaskExecutor getTaskExecutor() {
        return taskExecutor;
    }

    @Override
    public void start() {
        taskExecutor = new ThreadPoolTaskExecutor();
        // taskExecutor.setCorePoolSize(ConfigUtils.get("tbsp.adapter.socket.bfts.server.core.pool.size", Integer.class, 100));
        // taskExecutor.setMaxPoolSize(ConfigUtils.get("tbsp.adapter.socket.bfts.server.max.pool.size", Integer.class, 200));
        // taskExecutor.setQueueCapacity(ConfigUtils.get("tbsp.adapter.socket.bfts.server.queue.length", Integer.class, 100));
        taskExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        taskExecutor.setThreadNamePrefix("bftsServerSocket");
        taskExecutor.initialize();
        super.start();
        isRunning = true;
    }

    @Override
    public void stop() {
        if (isRunning) {
            isRunning = false;
            super.stop();
            taskExecutor.setWaitForTasksToCompleteOnShutdown(true);
            // 此处不等待其实也行，到这业务已经清空了
            taskExecutor.setAwaitTerminationSeconds(getTimeOut());
            taskExecutor.shutdown();
        }
    }

    @Override
    public boolean isStarted() {
        return isRunning;
    }
}
